package net.doglog;

import java.util.*;

import javax.jdo.*;

public class PageUtil {
	public static Page getPage(String pattern) {
		if (pattern == null) return null;
		Page page = null;
		PersistenceManager pm = PMF.pm();
		try {
			page = pm.getObjectById(Page.class, pattern);
			page = pm.detachCopy(page);
		} catch (JDOObjectNotFoundException e) {
			//page = null;
		} catch (JDOException e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return page;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Page> getAllPages() {
		List<Page> pages = null;
		PersistenceManager pm = PMF.pm();
		Query query = pm.newQuery(Page.class);
		try {
			pages = (List<Page>) query.execute();
			pages = (List<Page>) pm.detachCopyAll(pages);
		} catch (JDOException e) {
			pages = new ArrayList<Page>();
		} finally {
			query.closeAll();
			pm.close();
		}
		assert pages != null;
		return pages;
	}
	
	public static Page newPage(String pattern, String location) throws Throwable {
		if (pattern == null) throw new Throwable("invalid pattern");
		if (location == null) throw new Throwable("invalid location");
		pattern = pattern.trim(); location = location.trim();
		// pattern or location is allowed to be empty, but they can't be equal
		if (pattern.equals(location)) throw new Throwable("recursion detected");
		Page page = new Page(pattern, location);
		PersistenceManager pm = PMF.pm();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.makePersistent(page);
			tx.commit();
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
		return page;
	}
}